<template>
  <div class="merchantsList">
    <div class="zhezao" v-if="loadingShow">
      <i class="el-icon-loading" />数据加载中...
    </div>
    <div class="top">
      <div class="time pad">
        <span class="label">商户查询：</span>
        <el-input
          placeholder="商户编号\账号名称\店铺名称\手机号"
          v-model="filter.query"
          width="280px"
        >
        </el-input>
      </div>
      <div class="time pad">
        <span class="label">行业类型：</span>
        <el-cascader v-model="avalue" :options="typeLs" :show-all-levels="false" @change="handleChange">
        </el-cascader>
      </div>
      <div class="time pad">
        <span class="label">管辖区域：</span>
        <el-select v-model="filter.govArea" placeholder="请选择">
          <el-option v-for="item in areaSelect" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="time pad">
        <span class="label">邀请人：</span>
        <el-select v-model="filter.referrer" placeholder="请选择">
          <el-option v-for="item in referrerList" :key="item.id" :label="item.value" :value="item.id">
          </el-option>
        </el-select>
      </div>
      <div class="btn pad">
        <el-button @click="setReset">重置</el-button>
        <el-button type="primary" @click="search">查询</el-button>
      </div>
    </div>
    <div class="main">
      
      <div class="main_top">
        <div class="lef">
          <div class="" v-for="item in type" :class="['list', currentNavtab == item.id ? 'active' : '']" :key="item.id"
            :value="item.id" @click="handleTab(item.id)">
            {{ item.value }} <span>({{ item.num }})</span>
          </div>
        </div>
        <!-- <el-button type="primary" icon="el-icon-upload">导出</el-button> -->
        <div class="operate_box">
          <el-button type="primary" @click="addPhone">新增店铺</el-button>
          <div class="btnBox">
            <el-upload ref="elUpload" class="upload-demo" :action="fileaction" :headers="headers" :data="fileData"
              :limit="1" :show-file-list="false" :on-success="handleFileChange">
              <el-button type="primary">导入卡优优商户</el-button>
            </el-upload>
            <el-upload style="margin-left: 10px;" ref="elUpload" class="upload-demo" :action="shenyefileaction" :headers="headers" :data="fileData"
              :limit="1" :show-file-list="false" :on-success="handleFileChange">
              <el-button type="primary">导入神椰商户</el-button>
            </el-upload>
          </div>
        </div>
      </div>
      <ex-table ref="table"
        :table-column="tableColumn" :table-data="tableData" @pageSizeChange="handleSizeChange"
        @currentPageChange="handleCurrentChange">
        
        <template v-slot:source="{ scope }">
           <dict-tag :options="sourceList" :value="scope.row.source" />
        </template>
        <template v-slot:applyFunction="{ scope }">
           <dict-tag :options="applyFunctionList" :value="scope.row.applyFunction" />
        </template>
        <template v-slot:status="{ scope }">
           <dict-tag :options="statuslist" :value="scope.row.status" />
        </template>
        <template v-slot:operate="{ scope }">
          
          <el-button @click="getAudit(scope.row.id)" size="small" v-if="scope.row.status == 1">审核</el-button>
          <el-button @click="handleEdit(scope.row.id)" size="small" v-else-if="scope.row.status == 3 && scope.row.source == 3">编辑</el-button>
          <el-button @click="lookDetail(scope.row)" size="small" v-else>查看</el-button>
        </template>
      </ex-table>
      
    </div>
    <addDetailDialog v-if="addDetailDialog" :id="id" :pathType="pathType" :userData="userData" :visible.sync="addDetailDialog" @success="_handleSuccess" />
    <phoneDetailDialog v-if="phoneDetailDialog" :id="id" :visible.sync="phoneDetailDialog" @nextStep="_getPhone" /> 
    <auditDialog v-if="auditDialog" :id="id" :pathType="pathType" :visible.sync="auditDialog" @success="_handleSuccess" />
    <!--<puchCard-dialog v-if="detailDialog3" :id="id" :visible.sync="detailDialog3" @success="_handleSuccess" />
    <inviter-dialog v-if="inviterDialog" :id="id" :referrer="referrer" :visible.sync="inviterDialog"
      @success="_handleInviterSuccess" />
    <region-dialog v-if="regionDialog" :id="merchatId" :shopId="shopId" :type="typeStatus" :fromBase="fromBase"
      :visible.sync="regionDialog" @success="_handleSuccess" /> -->
  </div>
</template>
<script>
  import {
    mapState
  } from "vuex";
  // components
  import Loading from '@/components/Loading/index'
  import addDetailDialog from "./components/addDetailDialog";
  import phoneDetailDialog from "./components/phoneDetailDialog";
  import auditDialog from "./components/auditDialog";
  // import inviterDialog from "./components/merchantsList/inviterDialog";
  // import regionDialog from "./components/merchantsList/regionDialog"; 
  // api
  import {
    getList,
    merchantFundAccountList,
    shopTypeTree,
    setshopStatus,
    getDelete,
    merchantRedirect,
  } from "@/api/merchants";
  import {
    merchantList,
    statistics,
    referrer
  } from "@/api/merchants/merchantsAudit";
  import {
    userAreaSelect,
  } from "@/api/common";
  import {
    setTokenMarchant
  } from '@/utils/auth'
  // mixins
  import handlePageMixin from "@/mixins/handlePageMixin";
  import {
    getToken
  } from "@/utils/auth";
  export default {
    name: "NewIncreaseVerify",
    components: {
      addDetailDialog,
      phoneDetailDialog,
      auditDialog,
      Loading,
      // inviterDialog,
      // regionDialog,
    },
    mixins: [handlePageMixin],
    computed: {
      ...mapState({
        statusList: function (state) {
          return state.common["merchant_apply_status"]; // 要取this的实例，只能用不同函数，不能用箭头函数
        },
        industryStatusType: function (state) {
          return state.common["industry_type"]; // 要取this的实例，只能用不同函数，不能用箭头函数
        },
        shopTypeList: function (state) {
          return state.common["merchant_shop_status"]; // 要取this的实例，只能用不同函数，不能用箭头函数
        },
      }),
      ExportParams() {
        const {
          id: ticketId
        } = this;
        const params = {
          ...this.pageOptions,
          ...this.filter,
        };
        return params;
      },
    },
    data() {
      return {
        avalue: [],
        value: [],
        shopType: "",
        loading: false,
        loadingShow: true,
        detailDialog2: false,
        detailDialog3: false,
        inviterDialog: false,
        regionDialog: false,
        merchantLoading: false, //跳转商家后台loding
        type: [{
            id: '',
            value: "全部",
            num: ""
          },
          {
            id: 1,
            value: "待审核",
            num: 0
          },
          {
            id: 2,
            value: "已同意",
            num: 0
          },
          {
            id: 3,
            value: "已拒绝",
            num: 0
          },
          
        ],
        statuslist: [],
        sourceList: [],
        applyFunctionList: [],
        tableColumn: [{
            prop: "govArea",
            label: "管辖区域",
            width: "100"
          },
          {
            prop: "merchantId",
            label: "商户编号"
          },
          {
            prop: "merchantArea",
            label: "地区",
            width: "150"
          },
          {
            prop: "merchantName",
            label: "商户账号名称",
            width: "200"
          },
          {
            prop: "shopName",
            label: "店铺名称",
            width: "150"
          },
          {
            prop: "phone",
            label: "联系手机号",
            width: "140"
          },
           {
            prop: "shopTypeName",
            label: "行业类型",
            width: "140"
          },
          {
            prop: "applyTime",
            label: "申请时间",
            width: "160"
          },
          {
            slot: true,
            slotName: "source",
            label: "商户来源",
            width: "120"
          },
          {
            prop: "referrer",
            label: "邀请人",
            width: "160"
          },
          {
            slot: true,
            slotName: "applyFunction",
            label: "开通功能",
            width: "130"
          },
          {
            slot: true,
            slotName: "status",
            label: "审核状态",
            width: "100",
            
          },
          {
            label: "操作",
            slot: true,
            slotName: "operate",
            width: "150",
            fixed: "right",
          },
        ],
        filter: {
          govArea: "", //管辖区域
          query: "", //商户查询 商户编号\账号名称\店铺名称\手机号）
          referrer: "", //邀请人
          shopType: "",//行业类型
          status: '',
        },
        userData: {},
        tableData: [],
        currentNavtab: 0,
        addDetailDialog: false,
        phoneDetailDialog: false,
        auditDialog: false,
        normal: "",
        blacklist: "",
        isShow: true,
        AccountList: [], //关联资金账户查询列表
        // industryStatusType: [],//行业字典
        typeLs: [],
        id: "",
        merchatId: "",
        shopId: "",
        typeStatus: "", //注册状态  1 正常  2 待使用
        referrer: "",
        fromBase: {}, //传到子组件的数据
        areaSelect: [], //区域下拉
        cityOptions:[],//地区下拉
        cityValue:"",//选中的地区数据
        referrerList: [],
        pathType: 'add',
        fileaction: process.env.VUE_APP_BASE_API + "/merchant/register/apply/import/merchant",
        shenyefileaction: process.env.VUE_APP_BASE_API + "/merchant/register/apply/import/sy/merchant",
        headers: {
          'X-Access-Token': "Bearer " + getToken(),
        },
        fileData: {},
      };
    },

    created() {
      if(this.$route.query.id){
        this.currentNavtab = this.$route.query.id
        this.filter.status = this.$route.query.id
      }
      this.getDict()
      // this.getCity();
      this.getTypels();
      this.getUserAreaSelect();
      this.getmerchantFundAccountList();
      this.getList();
      this.getNum();
      this.getReferrer()

    },
    methods: {
      //获取邀请人下拉
      getReferrer(){
        var params = {}
        referrer(params).then(res => {
          this.referrerList = res.result
        })
      },
      getUserAreaSelect() {
        //查询用户区域下拉框
        userAreaSelect().then((res) => {
          var arr = [{
            id: "",
            value: "全部",
          }, ];
          this.areaSelect = arr.concat(res.result);
        });
      },
      //获取字典
      getDict() {
        console.log("hahahah");
        var dictType = "merchant_register_apply_function,merchant_register_source,merchant_register_apply_status";
        this.$getSelectList(dictType)
          .then((res) => {
            this.applyFunctionList = res.result[0].dictList;
            this.sourceList = res.result[1].dictList;
            this.statuslist = res.result[2].dictList;
          })
          .finally(() => {
          });
      },
      getTypels() {
        //shopTypeTree
        shopTypeTree()
          .then((res) => {
            let ls = [];
            // console.log("res.result+++", res.result);
            ls = this.getTreeData(res.result);
            // console.log(this.typeLs)
            let ls1 = ls.map((item) => {
              item.value = item.id;
              item.children.map((items) => {
                items.value = items.id;
              });
              return item;
            });
            // console.log("ls1+++", ls1);
            this.typeLs = ls1;
          })
          .finally(() => {
          });
      },
      getTreeData(data) {
        // 循环遍历json数据
        for (var i = 0; i < data.length; i++) {
          if (data[i].children.length < 1) {
            // children若为空数组，则将children设为undefined
            // data[i].children=undefined;
            delete data[i].children;
          } else {
            // children若不为空数组，则继续 递归调用 本方法
            this.getTreeData(data[i].children);
          }
        }
        return data;
      },
      //行业选择
      handleChange(value) { 
        let _this = this;
        console.log(value);
        if (value.length == 2) {
          _this.filter.shopType = value[1];
        } else {
          _this.filter.shopType = value[0];
        }
      },
      //获取资金账户列表
      getmerchantFundAccountList() {
        this.loading = true;
        merchantFundAccountList()
          .then((res) => {
            this.AccountList = res.result;
            // console.log(this.AccountList);
            if (this.AccountList.length != 0) {
              var arr = [{
                // id: "",
                merchantName: "全部",
              }, ];
              this.AccountList = arr.concat(this.AccountList);
            } else {}
          })
          .finally(() => {
            this.loading = false;
          });
      },
      //审核
      getAudit(id) {
        this.id = id;
        this.auditDialog = true;
        this.pathType = 'audit'
      },
      //编辑
      handleEdit(id){
        this.id = id;
        this.addDetailDialog = true
        this.pathType = 'edit'
      },
      //重新报备
      geReport(id) {
        this.id = id;
        this.detailDialog2 = true;
      },
      //查看详情
      lookDetail(e) {
        this.auditDialog = true
        this.id = e.id
        this.pathType = 'look'
      },
      addShop() { //创建店铺
        this.addDetailDialog = true
      },
      addPhone(){
        this.phoneDetailDialog = true
      },
      //导入成功
      handleFileChange(res, file) {
        if (res.code == 200) {
          this.$message.success('导入成功')
          this.setReset()
        } else {
          this.$message.error(res.message);
        }
        this.$refs.elUpload.clearFiles()
      },
      select(value) {
        console.log("select", value);
      },
      //切换选项
      handleTab(id) {
        this.loadingShow = false
        console.log("id", id)
        this.currentNavtab = id
        this.filter.status = id
        this.pageOptions.pageNum = 1
        this.getList();
      },
      //列表
      getList() {
        this.loading = true;
        this.loadingShow = true
        const params = {
          ...this.pageOptions,
          ...this.filter,
        };
        merchantList(params)
          .then((res) => {
            const {
              total,
              records
            } = res.result;
            records.forEach((item) => {
              item.industry = this.$getStatusText("industry_type", item.industry);
              if (item.cityName != "") {
                item.region =
                  item.provinceName + "-" + item.cityName + "-" + item.areaName; //处理地区
              } else {
                item.region = "-";
              }
              //处理注册状态
              if (item.type == 1) {
                item.typeDict = "正常";
              } else if (item.type == 2) {
                item.typeDict = "待使用";
              } else {
                item.typeDict = "-";
              }
              //判断是否为空，为空展示-
              for (var key in item) {
                if (!item[key]) {
                  item[key] = "-";
                }
              }
              if (item.applyStatus == 1) {
                item.isShow = true;
              } else {
                item.isShow = false;
              }
            });
            this.$refs.table.pageOptions.total = total;
            this.tableData = records;
          })
          .finally(() => {
            this.loadingShow = false,
            this.loading = false;
          });
      },
      //查询审核条数
      getNum() {
        this.loading = true;
        var params = {
          ...this.filter
        }
        delete params.status
        statistics(params)
          .then((res) => {
            // const { total,waitingAudit, normal, blacklist,refused } = res.result;
            this.type[0].num = res.result.total
            this.type[1].num = res.result.waitingAudit;
            this.type[2].num = res.result.agree;
            this.type[3].num = res.result.refused;
          })
          .finally(() => {
            this.loading = false;
          });
      },
      _handleSuccess() {
        this.getList();
        this.getNum();
        this.addDetailDialog = false;
        this.regionDialog = false;
      },
      //获取手机号
      _getPhone(data){
        console.log('data',data)
        this.addDetailDialog = true;
        this.pathType = "add"
        this.userData.account = data.account
        this.userData.password = data.password
      },
      //重置
      setReset() {
        this.filter.govArea = '';
        this.filter.referrer = "";
        this.filter.query = "";
        this.filter.shopType = "";
        this.avalue = []
        this.currentNavtab = 0
        this.filter.status = ''
        // this.filter.applyStatus = "";
        // this.filter.thirdMerchantNo = "";
        this.shopType = "";
        this.pageOptions.pageNum = 1;
        this.$refs.table.pageOptions.pageNum = 1;
        this.getList();
        this.getNum()
      },
      //搜索
      search() {
        this.pageOptions.pageNum = 1;
        this.$refs.table.pageOptions.pageNum = 1;
        this.getList();
        this.getNum()
      },
      _handleInviterSuccess() {
        this.getList();
        this.inviterDialog = false;
      },
    },
  };

</script>
<style lang="scss" scoped>
  @import "../style/merchantsList";

  .first_box {
    ::v-deep :nth-child(1).el-input__inner {
      width: 100px;
    }

    ::v-deep :nth-child(2).el-input__inner {
      width: 200px;
    }
  }

  .input-with-select .el-input-group__prepend {
    background-color: #fff;
  }
  .el-input{
    display: inline-block;
    position: relative;
    width: 260px;
  }
  .zhezao{
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #333;
    opacity: 0.6;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 99;
    color: #1890ff;;
  }
  .operate_box{
    display: flex;
    align-items: center;
  }
  .btnBox{
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-left: 20px;
  }
</style>
